<?php

namespace App\Http\Controllers;

use App\Models\ProfitSharingAccount;
use App\Models\ProfitSharingList;
use Illuminate\Http\Request;
use App\Contracts\WxProfitSharing;
use Illuminate\Support\Facades\Log;
use App\Events\ProfitShare;
use Illuminate\Support\Facades\Artisan;

class WxProfitShareController extends Controller
{
    /**
     * 支付回调
     *
     * @param Request $request
     */
    public function payNotify(Request $request)
    {
        $post = $request->post();

        Log::info('收到支付回调------------begin');
        Log::info($post);
        Log::info('收到支付回调------------end');

        event(new ProfitShare($post));
    }

    /**
     * 多次分账
     *
     * @param WxProfitSharing $wxProfitSharing
     * @return array
     * @throws \App\Contracts\Exception
     * @throws \Exception
     */
    public function multiShare(WxProfitSharing $wxProfitSharing)
    {
        return $wxProfitSharing->multiProfitSharing();
    }

    /**
     * 分账完结
     *
     * @param WxProfitSharing $wxProfitSharing
     * @return array
     * @throws \App\Contracts\Exception
     * @throws \Exception
     */
    public function finishAll(WxProfitSharing $wxProfitSharing)
    {
        return $wxProfitSharing->finishAll();
    }

    /**
     * 分账回退
     *
     * @param Request $request
     * @param WxProfitSharing $wxProfitSharing
     * @return array
     * @throws \App\Contracts\Exception
     * @throws \Exception
     */
     public function profitSharingReturn(Request $request )
    {
        $param = $request->all();
        $orderId = $param['OrderNo'];
        $profitOrder = ProfitSharingList::firstWhere('profit_sharing_order_id','like','%'.$orderId.'%');
        $wxProfitSharingAccount = ProfitSharingAccount::where('sub_appid',$profitOrder['sub_appid'])->first();
        
        //组装config
        $config = [
            'appCertPem'=>$wxProfitSharingAccount->app_certpem,
            'appKeyPem'=>$wxProfitSharingAccount->app_keypem,
            'appId' => $wxProfitSharingAccount->sub_appid,
            'mchId' => $wxProfitSharingAccount->sub_mchid,
            'md5Key' => $wxProfitSharingAccount->md5key,
            'is_mch' => $wxProfitSharingAccount->is_mch,
        ];
        Log::info('退款config ::' .json_encode($config));
        
        $wxProfitSharing = new WxProfitSharing($config);
        return $wxProfitSharing->profitSharingReturn($orderId);
    }
    // public function profitSharingReturn(Request $request, WxProfitSharing $wxProfitSharing)
    // {
    //     $orderId = $request->post('OrderNo');
    //     return $wxProfitSharing->profitSharingReturn($orderId);
    // }
}
